package io.gitee.skyarthur1987.leporidae.utils.base;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * 文件工具类
 * Created by skyarthur on 2023/1/26
 */
public class FileUtils {

    /**
     * 读取资源内容至 String
     *
     * @param resourcePath 资源路径, 相对 resources 目录
     * @param charset      文件编码
     * @return 文件内容
     * @throws IOException IO异常
     */
    public static String readResourceContents(String resourcePath, Charset charset) throws IOException {
        Assert.notNull(resourcePath, "resourcePath cannot be null");
        Assert.notNull(charset, "charset cannot be null");
        Resource resource = new ClassPathResource(resourcePath);
        return FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream(), charset));
    }

    /**
     * 按照 utf8 编码方式读取资源内容至 String
     *
     * @param resourcePath 资源路径, 相对 resources 目录
     * @return 文件内容
     * @throws IOException IO异常
     */
    public static String readResourceContents(String resourcePath) throws IOException {
        return readResourceContents(resourcePath, StandardCharsets.UTF_8);
    }
}
